const mongoose=require('mongoose');
const Cat=require('../models/cat.model');


exports.create=function(req,res,next){
    const cat=new Cat(req.body);
    cat.save().then(data=>{
        res.json(data);
    })
}

//update
exports.update=function(req,res,next){
    const id=req.params.id;
    
    Cat.findByIdAndUpdate(id,{$set:req.body},{ new: false }).then(data=>{
        res.json(data);
    });
}

//delete
exports.delete=function(req,res,next){
    const id=req.params.id;
    
    Cat.findByIdAndRemove(id,function(err,doc){
        res.json({status: 200,message:'数据删除成功'});
    });
};

//list
exports.list=function(req,res,next){
    const page=req.body.page? req.body.page:1;
    const rows=req.body.rows?req.body.rows:5;
    const queryCondition={};

    if(req.body.name && req.body.name.trim().length>0){
        queryCondition={
            name:new RegExp(name,'i')
        };
    }
    Cat.paginate(queryCondition,{page:+page,limit:+rows},function(err,result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
};